package com.chatplus.application.service.basedata.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatplus.application.dao.basedata.ConfigDao;
import com.chatplus.application.domain.dto.AdminConfigDto;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.dto.NoticeConfigDto;
import com.chatplus.application.domain.entity.basedata.ConfigEntity;
import com.chatplus.application.service.basedata.ConfigService;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

/**
 * 第三方AI配置表业务逻辑实现
 *
 * <p>Table: t_config - 第三方AI配置表</p>
 *
 * @author developer
 * @see ConfigEntity
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigDao, ConfigEntity> implements ConfigService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ConfigServiceImpl.class);

    private final ObjectMapper objectMapper;

    public ConfigServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public ConfigEntity getByMarker(String marker) {
        return this.getOne(new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getMarker, marker).last("limit 1"));
    }

    @Override
    public AdminConfigDto getSystemConfig() {
        try {
            ConfigEntity configEntity = getByMarker("system");
            if (configEntity == null) {
                return new AdminConfigDto();
            }
            return objectMapper.readValue(configEntity.getConfig(), AdminConfigDto.class);
        } catch (Exception e) {
            LOGGER.message("JSON转换失败").exception(e).error();
            return null;
        }
    }

    @Override
    public ChatConfigDto getChatConfig() {
        try {
            ConfigEntity configEntity = getByMarker("chat");
            if (configEntity == null) {
                return new ChatConfigDto();
            }
            return objectMapper.readValue(configEntity.getConfig(), ChatConfigDto.class);
        } catch (Exception e) {
            LOGGER.message("JSON转换失败").exception(e).error();
            return null;
        }
    }
    @Override
    public NoticeConfigDto getNoticeConfig() {
        try {
            ConfigEntity configEntity = getByMarker("notice");
            if (configEntity == null) {
                return new NoticeConfigDto("",false);
            }
            return objectMapper.readValue(configEntity.getConfig(), NoticeConfigDto.class);
        } catch (Exception e) {
            LOGGER.message("JSON转换失败").exception(e).error();
            return null;
        }
    }
}
